package com.ingenius.sau.server.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Blob;
import com.ingenius.sau.server.persistence.jdo.JdoBlobFileDAO;

@SuppressWarnings("serial")
public class FileDownloadService extends HttpServlet {

	public static final Map<String, Object> files = new HashMap<String, Object>();

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	public void destroy() {
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			java.io.IOException {

		String id = request.getParameter("id");
		BlobFile file = JdoBlobFileDAO.getInstance().getById(id);
		Blob b = file.getContent();
		response.setContentType("application/zip");
		response.setHeader("Content-Disposition", "attachment; filename="
				+ file.getName());
		response.getOutputStream().write(b.getBytes());
		response.getOutputStream().close();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			java.io.IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			java.io.IOException {
		processRequest(request, response);
	}

}
